package com.example.ai;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.ChatClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class SpringAiDemoApplication implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(SpringAiDemoApplication.class);

    // 注入Spring AI提供的ChatClient
    private final ChatClient chatClient;

    // 构造函数注入ChatClient
    public SpringAiDemoApplication(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringAiDemoApplication.class, args);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 应用启动成功后输出提示信息
        logger.info("Spring AI项目启动成功！访问 http://localhost:8080/ai/ask?question=你的问题");
        System.out.println("Spring AI项目启动成功！访问 http://localhost:8080/ai/ask?question=你的问题");
    }

    /**
     * 调用AI的接口：接收问题，返回AI回答
     * 支持更复杂的提示词逻辑，如格式化输出
     */
    @GetMapping("/ai/ask")
    public String askAi(@RequestParam String question,
                       @RequestParam(required = false, defaultValue = "text") String format) {
        // 构建更复杂的提示词
        String prompt;
        if ("json".equalsIgnoreCase(format)) {
            prompt = String.format("请以JSON格式回答以下问题：%s，JSON包含question和answer两个字段", question);
        } else {
            prompt = question;
        }
        
        // 调用AI模型生成回答
        return chatClient.prompt(prompt);
    }
}
